'''
@File    :   importCase.py.py    
@Contact :   kerici2005@163.com
@License :   (C)Copyright 2021-2023, Hunwei-NLPR-CASIA

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2021/7/19 14:50   Hunwei      1.0         None
'''
import os
import time
import openpyxl

from testapp.common.initPath import CASEFILE, DATADIR
from testapp.dataio.dataiofactory import DataIOFactory
from openpyxl.styles import Font



class ImportCase(object):
    def __init__(self):
        self.dataio = DataIOFactory()
        self.record = {}

    def savecasefile(self, file_obj):
        """
        保存导入的文件
        """
        try:
            self.record['viewname'] = file_obj.name
            save_name = str(round(time.time() * 1000000)) + '.xlsx'
            self.record['savename'] = save_name
            import os
            path = os.path.join(CASEFILE, save_name)  # 拼文件名的路径
            with open(path, "wb") as f:  # 写入文件
                for line in file_obj:
                    f.write(line)
            return True, save_name
        except Exception as e:
            return False, str(e)

    def judgeCate(self, rootcate, seccate, lastcate):
        """
        校验用例是否可以导入
        """
        isOK, result = self.dataio.getcaseCatebyName(rootcate)
        if isOK is False:
            return isOK, "未找到目录一，请检查"

        isOK, result = self.dataio.getcaseCateByparentId(result['id'])
        if isOK is False:
            return isOK, '未找到目录二，或级联不正确，请检查'
        parentid = -1
        cates = result
        for cate in cates:
            if seccate == cate['name']:
                parentid = cate['id']
                break
        if parentid == -1:
            return False, '未找到目录二，或级联不正确，请检查'

        isOK, result = self.dataio.getcaseCateByparentId(parentid)
        if isOK is False:
            return isOK, '未到找目录三，或级联不正确，请检查'
        cateid = -1
        cates = result
        for cate in cates:
            if lastcate == cate['name']:
                cateid = cate['id']
                break

        if cateid == -1:
            return False, '未找到目录三，或级联不正确，请检查'

        return True, cateid





    def getcasebyfile(self, f_name):
        """
        获取用例并格式化
        """
        try:
            path = os.path.join(CASEFILE, f_name)
            cases = []
            wb = openpyxl.open(path)
            font_false = Font(size=9, bold=True, color="FF0000")
            for sheet in wb:
                if sheet.title != '模板说明':
                    datas = list(sheet.rows)
                    count = len(datas)
                    self.record['casecount'] = count - 2
                    self.record['filcount'] = 0
                    title = [i.value for i in datas[1]]
                    row = 2
                    for i in datas[2:]:
                        cel = len(i) + 1
                        row = row + 1
                        data = [k.value for k in i]
                        case = dict(zip(title, data))
                        isOK, result = self.judgeCate(case['目录一'], case['目录二'], case['目录三'])

                        if isOK is False:  ##此处需要添加校验通过数据的统计与标记
                            sheet.cell(row, cel).value = result
                            sheet.cell(row, cel).font = font_false
                            self.record['filcount'] = self.record['filcount'] + 1
                            continue
                        if case['用例名称'] is None or case['用例名称'] == '':   ##此处需要添加校验通过数据的统计与标记
                            sheet.cell(row, cel).value = '用例名称必填，请检查'
                            sheet.cell(row, cel).font = font_false
                            self.record['filcount'] = self.record['filcount'] + 1
                            continue
                        case['catid'] = result
                        cases.append(case)
            wb.save(path)
            self.record['succount'] = self.record['casecount'] - self.record['filcount']
        except Exception as e:
            return False, str(e)
        return True, cases

    def addcase(self, cases):
        """
        写入用例入库
        """
        i_case = {}
        i_com = {}
        try:
            for case in cases:
                i_case['name'] = case['用例名称']
                i_case['catid'] = case['catid']
                i_case['api'] = case['接口路径']
                i_case['apimethod'] = case['接口类型']
                i_case['headers'] = case['请求头']
                i_case['body'] = case['请求体']
                i_case['checkrestype'] = case['校验数据'] == 'Response Header' and '0' or case['校验数据'] == 'Response Body' and '1' or case['校验数据'] == 'Status Code' and '2' or '0'
                i_case['checkmethod'] = case['校验方式']
                i_case['checkdata'] = case['校验值']

                isOK, result = self.dataio.insertCase(i_case)
                if isOK is False:
                    continue
                caseid = result
                if case['自定义方法-变量'] is not None \
                    or case['自定义方法'] is not None \
                    or case['自定义方法-参数1'] is not None \
                    or case['自定义方法-参数2'] is not None:
                    com = []
                    i_com['method'] = case['自定义方法']
                    i_com['f_params'] = case['自定义方法-参数1']
                    i_com['s_params'] = case['自定义方法-参数2']
                    i_com['result'] = case['自定义方法-变量']
                    com.append(i_com)
                    self.dataio.addCommonmehtod(com, 0, caseid)


                if case['数据库操作-变量'] is not None \
                    or case['数据库操作-SQL'] is not None \
                    or case['数据库操作-字段'] is not None:
                    com = []
                    i_com['method'] = ''
                    i_com['f_params'] = case['数据库操作-SQL']
                    i_com['s_params'] = case['数据库操作-字段']
                    i_com['result'] = case['数据库操作-变量']
                    com.append(i_com)
                    self.dataio.addCommonmehtod(com, 3, caseid)

                if case['参数化-变量'] is not None \
                    or case['参数化-方法'] is not None \
                    or case['参数化-定位参数'] is not None:
                    com = []
                    i_com['result'] = case['参数化-变量']
                    i_com['method'] = case['参数化-方法']
                    i_com['f_params'] = case['参数化-定位参数']
                    i_com['s_params'] = case['数据库操作-字段']
                    com.append(i_com)
                    self.dataio.addCommonmehtod(com, 4, caseid)
        except Exception as e:
            return False, str(e)

        return True, '导入数据成功'

    def saveImportRecord(self):
        """
        导入记录保存
        """
        return self.dataio.saveImportRecord(self.record)


    def importCase(self, file_obj):
        """
        导入入用例
        """
        isOK, result = self.savecasefile(file_obj)
        if isOK is False:
            return isOK, result

        isOK, result = self.getcasebyfile(result)
        if isOK is False:
            return isOK, result

        isOK, result = self.addcase(result)
        if isOK is False:
            return isOK, result

        isOK, result = self.saveImportRecord()
        if isOK is False:
            return isOK, result

        return isOK, '用例导入成功'

    def getImportFile(self, f_name, chunk_size=512):
        """
        打开导入用例记录文件
        """
        path = os.path.join(CASEFILE, f_name)
        with open(path, mode='rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break



    def getCaseModel(self):
        """
        打开用例模板
        """
        path = os.path.join(DATADIR, '用例模板.xlsx')
        with open(path, mode='rb') as f:
            while True:
                c = f.read(512)
                if c:
                    yield c
                else:
                    break

    def getHelpFile(self):
        """
        打开用例模板
        """
        path = os.path.join(DATADIR, '接口自动化平台使用手册.docx')
        with open(path, mode='rb') as f:
            while True:
                c = f.read(512)
                if c:
                    yield c
                else:
                    break